const _import = require('@/router/_import_' + process.env.NODE_ENV)
/* layout */
import Layout from '../../views/layout/Layout'
const permission = {
	state: {
		routers: [],
		addRouters: [],
		permissionsList:[]
	},
	mutations: {
		SET_ROUTERS: (state, data) => {        //生成路由表
			let routers = data.routers;
			let permissionsList = data.permissionsList;
			if(routers&&routers.length>0){
				for(let i=0;i<routers.length;i++){
					if(routers[i].children&&routers[i].children.length>0&&!routers[i].hips){
						for(let tempChildRoute of routers[i].children){
							let tempPath;
							if(tempChildRoute.path.indexOf("/")==0){
								tempPath = tempChildRoute.path.substring(1);
							}else{
								tempPath = tempChildRoute.path;
							}
							tempChildRoute.component = _import(tempPath);
						}
					}
					else{
						if(routers[i].children&&routers[i].children.length>0){
							let oneTemp={
								path: routers[i].path,
								component: Layout,
								name: routers[i].name,
								icon:routers[i].icon,
								hidden: routers[i].hidden,
								hips:true,
								transEng:routers[i].transEng,
								children: [
									{ path: routers[i].path,icon:routers[i].icon, component: _import(routers[i].path.substring(1)),name:'',hidden:true}
								]
							}
							for(let tempChildRoute of routers[i].children){
								let childTemp='';
								childTemp=tempChildRoute;
								let tempPath;
								if(tempChildRoute.path.indexOf("/")==0){
									tempPath = tempChildRoute.path.substring(1);
								}else{
									tempPath = tempChildRoute.path;
								}
								childTemp.component = _import(tempPath);
								oneTemp.children.push(childTemp)
							}
							routers[i]=oneTemp
						}
						else{
							let oneTemp={         //只有一级菜单(针对中加项目改造)
								path: routers[i].path,
								component: Layout,
								name: routers[i].name,
								icon:routers[i].icon,
								hips:true,
								hidden:routers[i].hidden,
								transEng:routers[i].transEng,
								children: [
									{ path: routers[i].path,icon:routers[i].icon, component: _import(routers[i].path.substring(1)),name:'',hidden:true}
								]
							}
							routers[i]=oneTemp
						}

					}
				}
			}
			state.addRouters = routers;
			state.routers = routers;
			state.permissionsList = permissionsList;
		}
	},
	actions: {
		GenerateRoutes({ commit }, data) {
			return new Promise(function(resolve){   //得到路由列表，包括所有权限路由和子路由
				let roles=data.roles;
				let permissionsList =data.permissionsList;
				let newRouters=[];
				roles.map((item, index) => {
					newRouters.push({
						path:item.path,
						component: Layout,
						name: item.name,
						hidden:item.hidden,
						icon:item.icon,
						children:item.children,
						transEng:item.transEng,
						hips:item.hips
					})
				})

				commit('SET_ROUTERS',{routers:newRouters,permissionsList:permissionsList})
				resolve()
			})
		}
	}
}

export default permission
